<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Robot\Robot;
use App\CustHub\Mapper\ChGetRobotMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\Robot\Service\RobotApiService;
use Hyperf\Di\Annotation\Inject;
use Mine\Exception\NormalStatusException;

class ChGetRobotService
{
    public $mapper;

    #[Inject]
    protected ChRobotMapper $robotMapper;

    #[Inject]
    protected RobotLoginService $robotLoginService;

    public function __construct(ChGetRobotMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function getRobot($params): array
    {
        return $this->mapper->getRobot($params);
    }

    public function changeServer(mixed $id,array $data)
    {
        $robot = $this->robotMapper->findById($id);

        if(empty($robot)){
            throw new NormalStatusException("请选择机器人");
        }

        if($robot->server_id == $data['server_id']){
            return true;
        }

        if($robot->login_status == 1){
            //需要先退出登录
            $service = make(Robot::class,[$robot->server_id,$robot->uuid])->gateway();
            $rst = $service->loginOut();
            if($rst === false){
                throw new NormalStatusException("操作失败，请重新操作");
            }

            $this->robotLoginService->loginOutNotify($robot);
        }

        $robot->server_id = $data['server_id'];
        $rst = $robot->save();
        $this->robotMapper->clearCache($robot->id);
        return $rst;
    }


}